<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<!-- Head -->

<head>
    <meta charset="utf-8" />
    <title>盲盒发布</title>

    <div th:replace="/system/resource/base/baseHead.template"></div>
    <link rel="stylesheet" type="text/css" th:href="${application.resourceUrl}+'/assets/js/lightbox/css/lightbox.css'" />
    <link rel="stylesheet" type="text/css" href="https://cdn.test.bestpay.net/orange/antd.1.6.5.css" />
    <!-- <link rel="stylesheet" type="text/css" href="./antd.1.6.5.css" /> -->
    <link rel="stylesheet" type="text/css" href="https://cdn.test.bestpay.net/orange/tailwindcss@2.2.19.min.css" />
    <style>
        [v-cloak] {
            visibility: hidden;
        }

        .limitBuyInfoVo {
            display: inline-block;
            background: #868686;
            margin: 0 5px 5px;
            padding: 2px 8px;
            border-radius: 5px;
            color: #fafafa;
        }

        .limitBuyInfoVoBox {
            text-overflow: -o-ellipsis-lastline;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            line-clamp: 2;
            -webkit-box-orient: vertical;
            position: relative;
            padding-right: 80px;
        }

        .limitBuyInfoVoBox-btn {
            position: absolute;
            right: 20px;
            bottom: 5px;
            padding: 2px 10px;
            background: #06beff;
            border-radius: 6px;
            color: #fefefe;
            cursor: pointer;
        }

        .goods-title {
            font-size: 18px;
            color: #000;
        }

        .goods-info-title {
            padding-left: 20px;
            padding-top: 10px;
            font-size: 16px;
            color: #000;
            display: flex;
            align-items: center;
        }

        .a-space {
            padding-top: 20px;
        }

        .goods-info-title-icon {
            cursor: pointer;
            color: #ff4d4f;
            font-size: 24px;
            margin-right: 5px;
        }

        .goods-info {
            border: 1px solid rgb(233 233 233);
            border-radius: 4px;
            margin-top: 10px;
            padding-bottom: 30px;
            margin-bottom: 20px;
        }

        .goods-title-btn {
            line-height: 40px;
        }

        .form-title-dlg {
            text-align: right;
            font-size: 14px;
            color: rgba(0, 0, 0, .85);
            line-height: 40px;
            margin-bottom: 24px;
        }

        .form-cnt {

            text-align: left;
            font-size: 14px;
            color: rgba(0, 0, 0, .85);
            line-height: 40px;
            margin-bottom: 24px;
        }

        .minus-circle-btn {
            cursor: pointer;
            color: #ff4d4f;
        }

        .mh-attr-input {
            width: 100%;
        }

        .a-price-form-col {
            display: flex;
        }

        .blindBoxCommodityInfoVOListTableD {
            margin-bottom: 16px;
        }

        .blindBoxCommodityInfoVOListTableD.ant-form-item-with-help {
            margin-bottom: 0px;
        }

        .blindBoxCommodityInfoVOListTableD .ant-form-explain {
            font-size: 12px;
            min-height: 17px;

        }

        .blindBoxSort {
            width: 100%;
        }

        .padding-bottom-0 {
            padding-bottom: 0;
        }
    </style>
</head>
<!-- /Head -->
<!-- Body -->

<body>
<!-- 引入头部 -->
<div th:include="/system/resource/base/baseNav.template"></div>
<!-- /引入头部 -->
<!-- Main Container -->
<div class="main-container container-fluid">
    <!-- Page Container -->
    <div class="page-container">
        <!-- 引入左侧菜单 -->
        <div class="page-sidebar" id="sidebar" th:include="/system/resource/base/baseLeftMenu.template"></div>
        <!-- /引入左侧菜单 -->
        <!-- Page Content -->
        <div class="page-content">
            <!-- Page Breadcrumb -->
            <div class="page-breadcrumbs">
                <ul class="breadcrumb"></ul>
            </div>
            <!-- /Page Breadcrumb -->
            <!-- Page Body -->
            <div id="app" class="page-body" v-cloak>
                <div v-if="showTablePage">
                    <a-card title="查询条件">
                        <a-form-model :model="searchForm" v-bind="layout">
                            <a-row>
                                <a-col :span="10">
                                    <a-form-model-item label="盲盒标题 :">
                                        <a-input v-model="searchForm.blindBoxName" placeholder="请输入盲盒标题" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="12">
                                    <a-form-model-item label="盲盒活动号 :">
                                        <a-input type="number" v-model="searchForm.blindBoxId" placeholder="请输入盲盒活动号" />
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                            <a-row>
                                <a-col :span="10">
                                    <a-form-model-item label="活动状态 :">
                                        <a-select v-model='searchForm.blindBoxStatus' placeholder="请选择">
                                            <a-select-option value="1">
                                                待开始
                                            </a-select-option>
                                            <a-select-option value="2">
                                                进行中
                                            </a-select-option>
                                            <a-select-option value="3">
                                                已结束
                                            </a-select-option>
                                        </a-select>
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="12">

                                    <a-form-model-item label="是否上架 :">
                                        <a-select v-model='searchForm.effective' placeholder="请选择">
                                            <a-select-option value="1">
                                                上架
                                            </a-select-option>
                                            <a-select-option value="0">
                                                下架
                                            </a-select-option>
                                        </a-select>
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                            <a-row>
                                <a-col :span="10">
                                    <a-form-model-item label="活动时间 :">
                                        <a-config-provider :locale="locales.zh_CN">
                                            <a-range-picker v-model="searchForm.blindBoxTime" />
                                        </a-config-provider>
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                            <a-row>
                                <a-col :span="24" :style="{ textAlign: 'center' }">
                                    <a-button @click="resetSearchFormInfo">
                                        重置
                                    </a-button>
                                    <a-button type="primary" :loading="queryTableLoading" :style="{ marginLeft: '8px' }"
                                              @click="onQueryTableData">
                                        查询
                                    </a-button>
                                </a-col>
                            </a-row>
                        </a-form-model>
                    </a-card>
                    <a-card title="查询结果">
                        <div slot="extra">
                            <a-button @click="onSetShowTablePage()" type="primary">
                                新增盲盒
                            </a-button>
                        </div>
                        <a-config-provider :locale="locales.zh_CN">
                            <a-table :columns="tableColumns" :data-source="tableData" :loading="loading" :pagination="pagination"
                                     row-key="id" :scroll="tableScroll" bordered size="small" @change="handleTableChange">
                                <!-- init(1, "待开始"), -->
                                <!-- proceed(2, "进行中"), -->
                                <!-- end(3, "已结束"); -->
                                <template slot="blindBoxStatus" slot-scope="text, record, index">
                                    <div v-if="record.blindBoxStatus == 'init'">待开始</div>
                                    <div v-if="record.blindBoxStatus == 'proceed'">进行中</div>
                                    <div v-if="record.blindBoxStatus == 'end'">已结束</div>
                                </template>
                                <template slot="activeTime" slot-scope="text, record, index">
                                    <div>{{record.blindBoxStartTime.split(" ")[0]}}~{{record.blindBoxEndTime.split(" ")[0]}}</div>
                                </template>
                                <template slot="action" slot-scope="text, record, index">
                                    <a-button type="primary" @click="showDetailDialog(record)">详情</a-button>
                                    <a-button type="danger" v-if="record.effective == 'FALSE'" @click="onblindBoxSoldOut(record)">上架
                                    </a-button>
                                    <a-button type="danger" v-if="record.effective == 'TRUE'" @click="onblindBoxSoldOut(record)">下架
                                    </a-button>
                                    <a-button @click="onSetShowTablePage(record)">
                                        修改
                                    </a-button>
                                </template>
                            </a-table>
                        </a-config-provider>
                    </a-card>
                </div>

                <a-form-model v-else :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" :model="dialogForm" ref="ruleForm">
                    <a-card :title="dialogFormDisable? (isEdit ?'修改盲盒' :'盲盒详情' ):'新增盲盒'">
                        <div class="goods-title">商品信息</div>
                        <div class="goods-info" v-for="(item,formIndex) in dialogForm.blindBoxCommodityInfoVOList"
                             :key="formIndex">
                            <div class="goods-info-title"> 商品{{formIndex+1}} ：
                                <div v-show="!dialogFormDisable">
                                    <a-icon type="plus-square" class="goods-info-title-icon" @click="onAddGoodsForm(formIndex)" />
                                </div>
                                <div v-show="!dialogFormDisable" v-if="dialogForm.blindBoxCommodityInfoVOList.length > 1">
                                    <a-icon type="minus-square" class="goods-info-title-icon" @click="onDelGoodsForm(formIndex)" />
                                </div>
                            </div>
                            <a-row>
                                <a-col :span="1"></a-col>
                                <a-col :span="7">
                                    <a-form-model-item label="商品编码 :" :rules="dialogFormRules.spuId"
                                                       :prop="'blindBoxCommodityInfoVOList.' + formIndex + '.spuId'">
                                        <a-input :disabled="dialogFormDisable" v-model="item.spuId" placeholder="请输入商品编码" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="7" class="goods-title-btn">
                                    <a-button v-if="!dialogFormDisable" @click="dialogSupIdClick(formIndex)">确认</a-button>
                                </a-col>
                            </a-row>
                            <a-row v-if="item.commodityMainTitle">
                                <a-col class="form-title-dlg " :span="3">商品主标题：</a-col>
                                <a-col class="form-cnt" :span="5">{{item.commodityMainTitle}}</a-col>
                                <a-col class="form-title-dlg " :span="2">类目：</a-col>
                                <a-col class="form-cnt" :span="6">{{item.categoryName}}</a-col>
                                <a-col class="form-title-dlg " :span="3">品牌名称：</a-col>
                                <a-col class="form-cnt" :span="5">{{item.brandName}}</a-col>
                            </a-row>
                            <a-row v-if="item.commodityMainTitle">
                                <a-col :span="1"></a-col>
                                <a-col :span="7">
                                    <a-form-model-item label="商家名称 :" :rules="dialogFormRules.merchantId"
                                                       :prop="'blindBoxCommodityInfoVOList.' + formIndex + '.merchantVo.merchantId'">
                                        <a-select :disabled="dialogFormDisable" v-model="item.merchantVo.merchantId" placeholder="请选择商家名称"
                                                  @change="dialogMerchantNameSelect($event,formIndex)" allowClear>
                                            <a-select-option v-for="merchantItem in item.merchantSelectOptions"
                                                             :key="merchantItem.merchantId" :value="merchantItem.merchantId">{{
                                                merchantItem.merchantName }}</a-select-option>
                                        </a-select>
                                    </a-form-model-item>
                                </a-col>
                                <a-col class="form-title-dlg " :span="3">商家ID：</a-col>
                                <a-col class="form-cnt" :span="7">
                                    {{item.merchantVo.merchantId}}
                                </a-col>
                            </a-row>
                            <a-row v-if="item.attrVos.length" v-for="(attr,k) in item.attrVos" :key="k">
                                <a-col :span="1"></a-col>
                                <a-col :span="7">
                                    <a-form-model-item label="属性 :">
                                        <a-select :disabled="true" allowClear v-model:value="attr.attributeId" placeholder="请选择">
                                            <a-select-option v-for="(itm,index) in item.attrVos" :value="itm.attributeId">
                                                {{itm.attributeName}}</a-select-option>
                                        </a-select>
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="1"></a-col>
                                <a-col :span="7">
                                    <a-form-model-item label="属性值 :" :rules="dialogFormRules.attributeValueId"
                                                       :prop="'blindBoxCommodityInfoVOList.' + formIndex + '.attrVos.' + k + '.value'" allowClear>
                                        <a-select mode="multiple" :disabled="dialogFormDisable" v-model="item.attrVos[k].value"
                                                  @change="dialogMerchantAttrSelect($event,formIndex,k)" allowClear placeholder="请选择">
                                            <a-select-option v-for="(itm,index) in attr.children"
                                                             :value="itm.attributeId+'&'+itm.attributeValueId">{{itm.attributeValueName}}</a-select-option>
                                        </a-select>
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                            <a-row v-if="item.tableDataList && item.tableDataList.length" class="goods-attr-table">
                                <a-col :span="2"></a-col>
                                <a-col :span="20">
                                    <a-table :columns="item.tableRowList" :pagination="false" bordered :scroll="{ x: 900, y: 300 }"
                                             :data-source="item.tableDataList" size="small">
                                        <!-- 盲盒商品件数 -->
                                        <template slot="mhSlot1" slot-scope="text, record, tbindex">
                                            <a-form-model-item class="blindBoxCommodityInfoVOListTableD" label="" :label-col="{ span: 0 }"
                                                               :wrapper-col="{ span: 24 }" :rules="dialogFormRules.commodityStock"
                                                               :prop="'blindBoxCommodityInfoVOList.' + formIndex + '.tableDataList.'+tbindex + '.commodityStock'">
                                                <a-input-number class="mh-attr-input" precision="0" :disabled="dialogFormDisable"
                                                                v-model="item.tableDataList[tbindex].commodityStock" placeholder="请填写" />
                                            </a-form-model-item>
                                        </template>
                                        <!-- 试玩件数 -->
                                        <template slot="mhSlot2" slot-scope="text, record, tbindex">
                                            <a-form-model-item label="" class="blindBoxCommodityInfoVOListTableD" :label-col="{ span: 0 }"
                                                               :wrapper-col="{ span: 24 }" :rules="dialogFormRules.demoStock"
                                                               :prop="'blindBoxCommodityInfoVOList.' + formIndex + '.tableDataList.'+tbindex + '.demoStock'">
                                                <a-input-number class="mh-attr-input" :disabled="dialogFormDisable" precision="0"
                                                                v-model="item.tableDataList[tbindex].demoStock" placeholder="请填写" />
                                            </a-form-model-item>
                                        </template>
                                        <!-- 商品等级 -->
                                        <template slot="mhSlot3" slot-scope="text, record, tbindex">
                                            <a-form-model-item label="" class="blindBoxCommodityInfoVOListTableD" :label-col="{ span: 0 }"
                                                               :wrapper-col="{ span: 24 }" :rules="dialogFormRules.commodityGrade"
                                                               :prop="'blindBoxCommodityInfoVOList.' + formIndex + '.tableDataList.'+tbindex + '.commodityGrade'">
                                                <a-select class="mh-attr-input" :disabled="dialogFormDisable"
                                                          v-model='item.tableDataList[tbindex].commodityGrade' allowClear placeholder="请选择">
                                                    <a-select-option value="2">
                                                        普通款
                                                    </a-select-option>
                                                    <a-select-option value="1">
                                                        稀有款
                                                    </a-select-option>
                                                </a-select>
                                            </a-form-model-item>
                                        </template>
                                        <!-- mhSlot4 -->
                                        <template slot="mhSlot4" slot-scope="text, record, tbindex">
                                            <a-form-model-item label="" class="blindBoxCommodityInfoVOListTableD" :label-col="{ span: 0 }"
                                                               :wrapper-col="{ span: 24 }" :rules="dialogFormRules.returnRatio"
                                                               :prop="'blindBoxCommodityInfoVOList.' + formIndex + '.tableDataList.'+tbindex + '.returnRatio'">
                                                <a-input class="mh-attr-input" :disabled="dialogFormDisable" precision="0"
                                                         v-model="item.tableDataList[tbindex].returnRatio" placeholder="请填写"  suffix="%"  >
                                                </a-input>
                                            </a-form-model-item>
                                        </template>
                                        <!-- probability -->
                                        <template slot="probability" slot-scope="text, record, index">
                                            {{(record.probability*100).toFixed(2)}}%
                                        </template>
                                        <!-- 操作 -->
                                        <template slot="action" slot-scope="text, record, index">
                                            <a-icon type="minus-circle" class="minus-circle-btn"
                                                    @click="removeAttrs(record, index , formIndex)" />
                                        </template>
                                    </a-table>
                                </a-col>
                                <a-col :span="2"></a-col>
                            </a-row>
                        </div>
                        <div class="goods-title">盲盒信息</div>
                        <div class="goods-info">
                            <div class="a-space"></div>
                            <a-row>
                                <a-col :span="1"></a-col>
                                <a-col :span="23" style="text-align: left;">

                                    <a-form-model-item :rules="dialogFormRules.mainPhotoImgList" prop="mainPhotoImgList"
                                                       :label-col="{ span: 2 }" :wrapper-col="{ span: 22 }" label="上传盲盒图片 :">
                                        <div class="flex">
                                            <div class="relative w-24 h-24 mr-1" v-for="(photo, index) in dialogForm.mainPhotoImgList"
                                                 :key="index" @dragenter="dragenter($event, index, 'main')" @dragover="dragover($event, index)"
                                                 @dragstart="dragstart(index)" :draggable="!dialogFormDisable">
                                                <img class="w-full h-full" :src="photo.pictureUrl">
                                                <div 
                                                     class="photoOverlay absolute top-0 left-0 flex items-center justify-center w-full h-full"
                                                     style="background-color: rgba(0, 0, 0, 0.5);">
                                                    <a-icon @click="photoDelete(index, 'main')" class="cursor-pointer"
                                                            :style="{fontSize: '20px', color: 'white'}" type="delete" />
                                                </div>
                                            </div>
                                            <label  for="mainPhotoInput"
                                                   class="flex border items-center justify-center flex-col w-24 h-24">
                                                <a-icon type="plus" :style="{fontSize: '40px'}"></a-icon>
                                            </label>
                                            <input id="mainPhotoInput" type="file" accept="image/*" style="display: none;"
                                                   ref="mainPhotoInput" @change="photoInputChange('main')" />
                                        </div>
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                            <a-row>
                                <a-col :span="1"></a-col>
                                <a-col :span="7">
                                    <a-form-model-item label="盲盒标题 :" :rules="dialogFormRules.blindBoxName"
                                                       prop="blindBoxVO.blindBoxName">
                                        <a-input v-if="isEdit" v-model="dialogForm.blindBoxVO.blindBoxName" placeholder="请输入盲盒标题" @change="onChangeBilndBoxName" >
                                        </a-input>
                                        <a-input v-else @change="onChangeBilndBoxName":disabled="dialogFormDisable" v-model="dialogForm.blindBoxVO.blindBoxName"
                                                 placeholder="请输入盲盒标题"></a-input>
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="1"></a-col>
                                <a-col :span="7">
                                    <a-form-model-item label="盲盒排序 :" :rules="dialogFormRules.blindBoxSort"
                                                       prop="blindBoxVO.blindBoxSort">
                                        <a-input-number v-if="isEdit" class="blindBoxSort" v-model="dialogForm.blindBoxVO.blindBoxSort"
                                                        placeholder="请设置盲盒排序"></a-input-number>
                                        <a-input-number v-else class="blindBoxSort" :disabled="dialogFormDisable"
                                                        v-model="dialogForm.blindBoxVO.blindBoxSort" placeholder="请设置盲盒排序"></a-input-number>
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                            <a-row>
                                <a-col :span="1"></a-col>
                                <a-col :span="7">
                                    <a-form-model-item label="活动日期 :" :rules="dialogFormRules.blindBoxActiveTime"
                                                       prop="blindBoxVO.blindBoxActiveTime">
                                        <a-config-provider :locale="locales.zh_CN">
                                            <a-range-picker :disabled-date="disabledStartDate" :disabled="dialogFormDisable"
                                                            @change="onBlindBoxActiveTimeChange" v-model="dialogForm.blindBoxVO.blindBoxActiveTime"
                                                            :ranges="{ '今日': [moment(), moment()], '本月': [moment(), moment().endOf('month')] }"
                                                            placeholder="请设置活动日期" />
                                        </a-config-provider>
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="1"></a-col>
                                <a-col :span="7">
                                    <a-form-model-item label="盲盒标签 :" :rules="dialogFormRules.blindBoxTag"
                                                       prop="blindBoxVO.blindBoxTag">
                                        <a-select mode="tags" v-if="isEdit" v-model="dialogForm.blindBoxVO.blindBoxTag" size="default"
                                                  placeholder="盲盒标签若多个请以，分隔" @change="onBlindBoxTagChange">
                                        </a-select>
                                        <a-select mode="tags" v-else :disabled="dialogFormDisable"
                                                  v-model="dialogForm.blindBoxVO.blindBoxTag" size="default" placeholder="盲盒标签若多个请以，分隔"
                                                  @change="onBlindBoxTagChange">
                                        </a-select>
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                        </div>
                        <div class="goods-title">价格信息</div>
                        <div class="goods-info">
                            <div class="a-space"></div>
                            <a-row>
                                <a-col :span="1"></a-col>
                                <a-col class="a-price-form-col" :span="23">
                                    <a-form-model-item :label-col="{ span: 11 }" :wrapper-col="{ span: 8 }" label="单抽原价 :"
                                                       :rules="dialogFormRules.onceOriginalPrice" prop="priceVO.onceOriginalPrice">
                                        <a-input :disabled="dialogFormDisable" v-model="dialogForm.priceVO.onceOriginalPrice"
                                                 placeholder="填写">
                                            <a-tooltip slot="suffix" title="">
                                                元
                                            </a-tooltip>
                                        </a-input>
                                    </a-form-model-item>
                                    <a-form-model-item :label-col="{ span: 11 }" :wrapper-col="{ span: 8 }" label="N开不重原价 :"
                                                       :rules="dialogFormRules.continuousOriginalPrice" prop="priceVO.continuousOriginalPrice">
                                        <a-input :disabled="dialogFormDisable" v-model="dialogForm.priceVO.continuousOriginalPrice"
                                                 placeholder="填写">
                                            <a-tooltip slot="suffix" title="">
                                                元
                                            </a-tooltip>
                                        </a-input>
                                    </a-form-model-item>
                                    <a-form-model-item label="N=" :label-col="{ span: 4 }" :wrapper-col="{ span: 8 }"
                                                       :rules="dialogFormRules.continuousNum" prop="priceVO.continuousNum">
                                        <a-input :disabled="dialogFormDisable" v-model="dialogForm.priceVO.continuousNum"
                                                 placeholder="填写">
                                            <a-tooltip slot="suffix" title="">
                                                开
                                            </a-tooltip>
                                        </a-input>
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                            <a-row>
                                <a-col :span="1"></a-col>
                                <a-col class="a-price-form-col" :span="23">
                                    <a-form-model-item :label-col="{ span: 11 }" :wrapper-col="{ span: 8 }" label="单抽限时优惠价 :"
                                                       :rules="dialogFormRules.onceDiscountsPrice" prop="priceVO.onceDiscountsPrice">
                                        <a-input :disabled="dialogFormDisable" v-model="dialogForm.priceVO.onceDiscountsPrice"
                                                 placeholder="填写">
                                            <a-tooltip slot="suffix" title="">
                                                元
                                            </a-tooltip>
                                        </a-input>
                                    </a-form-model-item>
                                    <a-form-model-item :label-col="{ span: 11 }" :wrapper-col="{ span: 8 }" label="N开不重限时优惠价 :"
                                                       :rules="dialogFormRules.continuousDiscountsPrice" prop="priceVO.continuousDiscountsPrice">
                                        <a-input :disabled="dialogFormDisable" v-model="dialogForm.priceVO.continuousDiscountsPrice"
                                                 placeholder="填写">
                                            <a-tooltip slot="suffix" title="">
                                                元
                                            </a-tooltip>
                                        </a-input>
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                            <a-row>
                                <a-col :span="1"></a-col>
                                <a-col class="a-price-form-col" :span="23">
                                    <a-form-model-item :label-col="{ span: 11 }" :wrapper-col="{ span: 8 }" label="单抽首单优惠价 :"
                                                       :rules="dialogFormRules.onceFirstPrice" prop="priceVO.onceFirstPrice">
                                        <a-input :disabled="dialogFormDisable" v-model="dialogForm.priceVO.onceFirstPrice"
                                                 placeholder="填写">
                                            <a-tooltip slot="suffix" title="">
                                                元
                                            </a-tooltip>
                                        </a-input>
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                        </div>
                        <div class="goods-title">概率信息</div>
                        <div class="goods-info padding-bottom-0">
                            <a-row>
                                <a-col class="form-title-dlg " :span="3">稀有款概率：</a-col>
                                <a-col class="form-cnt" :span="5">{{xyprobability}}</a-col>
                                <a-col class="form-title-dlg " :span="3">普通款概率：</a-col>
                                <a-col class="form-cnt" :span="5">{{ptprobability}}</a-col>
                                <a-col class="form-title-dlg " :span="3"></a-col>
                                <a-col :span="5"></a-col>
                            </a-row>
                        </div>
                        <a-row>
                            <a-col class="form-title-dlg " :span="2">
                                <a-button type="primary" v-if="isEdit || !dialogFormDisable" :loading="editBtnLoading"
                                          @click="onSubmit(true)">
                                    确认
                                </a-button>
                            </a-col>
                            <a-col class="form-title-dlg " :span="2">
                                <a-button :loading="editBtnLoading" @click="onSubmit(false)">
                                    返回
                                </a-button>
                            </a-col>
                        </a-row>
                    </a-card>

                </a-form-model>
            </div>
        </div>
    </div>

    <!-- /Page Body -->
</div>
<!-- /Page Content -->
<div th:replace="/system/resource/base/baseFoot.template"></div>
<script
        th:src="${application.resourceUrl}+'/assets/js/datatable/jquery.dataTables.min.js?'+${application.JSVERSION}"></script>
<script
        th:src="${application.resourceUrl}+'/assets/js/datatable/dataTables.tableTools.min.js?'+${application.JSVERSION}"></script>
<script
        th:src="${application.resourceUrl}+'/assets/js/datatable/dataTables.bootstrap.min.js?'+${application.JSVERSION}"></script>
<script th:src="${application.resourceUrl}+'/bboss/js/datatable/DT_bootstrap.js?'+${application.JSVERSION}"></script>
<script
        th:src="${application.resourceUrl}+'/assets/js/validation/bootstrapValidator.js?'+${application.JSVERSION}"></script>
<script
        th:src="${application.resourceUrl}+'/assets/js/validation/bootstrapValidator_zh_CN.js?'+${application.JSVERSION}"></script>
<script
        th:src="${application.resourceUrl}+'/bboss/js/validator/bootstrapValidator-extend.js?'+${application.JSVERSION}"></script>
<script
        th:src="${application.resourceUrl}+'/bboss/js/datatable/datatable_client.js?'+${application.JSVERSION}"></script>
<script
        th:src="${application.resourceUrl}+'/bboss/js/datatable/datatable_server.js?'+${application.JSVERSION}"></script>
<script th:src="${application.resourceUrl}+'/bboss/js/form/form.js?'+${application.JSVERSION}"></script>
<script th:src="${application.resourceUrl}+'/assets/js/select2/select2.min.js?'+${application.JSVERSION}"></script>
<script th:src="${application.resourceUrl}+'/bboss/js/select2/selectTab.js?'+${application.JSVERSION}"></script>
<script th:src="${application.resourceUrl}+'/bboss/js/dialog/dialog-page.js?'+${application.JSVERSION}"></script>
<script
        th:src="${application.resourceUrl}+'/bboss/js/dialog/bboss-dialog-page.js?'+${application.JSVERSION}"></script>
<script
        th:src="${application.resourceUrl}+'/assets/js/jquery-file-upload/js/vendor/jquery.ui.widget.js?'+${application.JSVERSION}"></script>
<script
        th:src="${application.resourceUrl}+'/assets/js/jquery-file-upload/js/jquery.iframe-transport.js?'+${application.JSVERSION}"></script>
<script
        th:src="${application.resourceUrl}+'/assets/js/jquery-file-upload/js/jquery.fileupload.js?'+${application.JSVERSION}"></script>
<script th:src="${application.resourceUrl}+'/assets/js/lightbox/js/lightbox.js?'+${application.JSVERSION}"></script>
<script th:src="${application.resourceUrl}+'/bboss/js/upload/bboss-fileUpload.js?'+${application.JSVERSION}"></script>

<script src="https://cdn.test.bestpay.net/orange/moment-with-locales.min.js"></script>
<script src="https://cdn.test.bestpay.net/orange/vue.2.6.9.js"></script>
<script src="https://cdn.test.bestpay.net/orange/antd.1.6.5.js"></script>
<script src="https://cdn.test.bestpay.net/orange/axios.0.20.0.js"></script>
<script src="https://cdn.test.bestpay.net/orange/antd-with-locales.1.6.5.js"></script>

<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment-with-locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.9/vue.min.js"></script>
<script src="./antd.1.6.5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.0/axios.min.js"></script>
<script src="./antd-with-locales.1.6.5.js"></script> -->

<!--Page Related Scripts-->
<script th:inline="javascript">
    /**
     * 增强版：解决js计算丢失精度的问题
     */
    var floatObj = function () {
        /*
         * 判断obj是否为一个整数
         */
        function isInteger (obj) {
            return Math.floor(obj) === obj;
        }

        /*
         * 将一个浮点数转成整数，返回整数和倍数。如 3.14 >> 314，倍数是 100
         * @param floatNum {number} 小数
         * @return {object}
         *   {times:100, num: 314}
         */
        function toInteger (floatNum) {
            var ret = { times: 1, num: 0 };
            var isNegative = floatNum < 0;
            if (isInteger(floatNum)) {
                ret.num = floatNum;
                return ret;
            }
            var strfi = floatNum + '';
            var dotPos = strfi.indexOf('.');
            var len = strfi.substr(dotPos + 1).length;
            var times = Math.pow(10, len);
            var intNum = parseInt(Math.abs(floatNum) * times + 0.5, 10);
            ret.times = times;
            if (isNegative) {
                intNum = -intNum;
            }
            ret.num = intNum;
            return ret;
        }

        /*
         * 核心方法，实现加减乘除运算，确保不丢失精度
         * 思路：把小数放大为整数（乘），进行算术运算，再缩小为小数（除）
         *
         * @param a {number} 运算数1
         * @param b {number} 运算数2
         * @param digits {number} 精度，保留的小数点数，比如 2, 即保留为两位小数
         * @param op {string} 运算类型，有加减乘除（add/subtract/multiply/divide）
         *
         */
        function operation (a, b, digits, op) {
            var o1 = toInteger(a);
            var o2 = toInteger(b);
            var n1 = o1.num;
            var n2 = o2.num;
            var t1 = o1.times;
            var t2 = o2.times;
            var max = t1 > t2 ? t1 : t2;
            var result = null;
            switch (op) {
                case 'add':
                    if (t1 === t2) { // 两个小数位数相同
                        result = n1 + n2;
                    } else if (t1 > t2) { // o1 小数位 大于 o2
                        result = n1 + n2 * (t1 / t2);
                    } else { // o1 小数位 小于 o2
                        result = n1 * (t2 / t1) + n2;
                    }
                    return (result / max).toFixed(digits);
                case 'subtract':
                    if (t1 === t2) {
                        result = n1 - n2;
                    } else if (t1 > t2) {
                        result = n1 - n2 * (t1 / t2);
                    } else {
                        result = n1 * (t2 / t1) - n2;
                    }
                    return (result / max).toFixed(digits);
                case 'multiply':
                    result = (n1 * n2) / (t1 * t2);
                    return result.toFixed(digits);
                case 'divide':
                    result = (n1 / n2) * (t2 / t1);
                    return result.toFixed(digits);
            }
        }

        // 加减乘除的四个接口  加减乘除（add/subtract/multiply/divide）
        function add (a, b, digits) {
            return operation(a, b, digits, 'add');
        }
        function subtract (a, b, digits) {
            return operation(a, b, digits, 'subtract');
        }
        function multiply (a, b, digits) {
            return operation(a, b, digits, 'multiply');
        }
        function divide (a, b, digits) {
            return operation(a, b, digits, 'divide');
        }

        // exports
        return {
            add: add,
            subtract: subtract,
            multiply: multiply,
            divide: divide
        };
    }();

    function jsonSecurity (url) {
        url = url.replace(/\\/g, "@@"); //反斜杠转换为@@
        url = url.replace(/\$/g, "--"); //$符转换为--
        url = url.replace(/\|/g, "^^"); //竖杠转换为^^
        url = url.replace(/%/g, "!!");  //%转换为!!
        url = url.replace(/\"/g, "=="); //双引号转换为==
        url = url.replace(/\'/g, "**"); //单引号转换为**
        return url;
    };
    // 所有 接口链接
    const apiUrlConfig = {
        // 查询类目列表
        categoryUrl: '/PF/service/shoppingMallConfigurationService/commodityCategoryTreeQuery.do',
        // 查询盲盒列表
        queryList: '/PF/service/excellentBlindBoxService/blindBoxQuery.do',
        // 盲盒详情
        blindBoxDetailQuery: '/PF/service/excellentBlindBoxService/blindBoxDetailQuery.do',
        // /PF/service/excellentBlindBoxService/blindBoxDetailQuery.do

        // 新增盲盒
        blindBoxAdd: '/PF/service/excellentBlindBoxService/blindBoxAdd.do',
        // 修改盲盒
        blindBoxModify: '/PF/service/excellentBlindBoxService/blindBoxModify.do',

        // 查询商品信息
        activityCommodityQueryForSpuId: '/PF/service/excellentActivityFacade/activityCommodityQueryForSpuId.do',
        // 查询属性表格和商品图片
        activitySkuQueryForMerchant: '/PF/service/excellentActivityFacade/activitySkuQueryForMerchant.do',
        // 盲盒上下架
        blindBoxSoldOut: '/PF/service/excellentBlindBoxService/blindBoxSoldOut.do',
    }
    const atobBtoaUtils = {
      // 转码
      btoa(str){
        return str
        // return (encodeURI(str))
        // return window.btoa(encodeURI(str))
      },
      // 解码
      atob(str){
        return str
        // return decodeURI(str)

        // return decodeURI(window.atob(str))
      },
    }
    const http = axios.create({
        timeout: 10000, // 请求超时时间
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        transformRequest: [function (data) {
            let ret = ''
            for (let it in data) {
                if (typeof data[it] === 'string') {
                    ret += encodeURIComponent(it) + '=' + jsonSecurity(data[it]) + '&'
                } else {
                    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                }
            }
            return ret
        }],
    });
    http.interceptors.response.use(response => {
        return response.data;
    });

    function getBase64 (file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result);
            reader.onerror = error => reject(error);
        });
    }
    const { locales } = window.antd;
    tableColumnsWidth = window.screen.width * 0.12
    /** 表格数据列配置 */
    const tableColumns = [
        {
            title: 'id',
            dataIndex: 'id',
            align: 'center',
            width: 80,
        },
        {
            title: '盲盒标题',
            dataIndex: 'blindBoxName',
            align: 'center',
            width: tableColumnsWidth,
        },
        {
            title: '盲盒活动号',
            dataIndex: 'blindBoxId',
            align: 'center',
            width: tableColumnsWidth,
        },
        {
            title: '活动状态',
            dataIndex: 'blindBoxStatus',
            align: 'center',
            scopedSlots: { customRender: 'blindBoxStatus' },
            width: tableColumnsWidth,
        },
        {
            title: '活动时间',
            width: window.screen.width * 0.15,
            dataIndex: 'activeTime',
            align: 'center',
            scopedSlots: { customRender: 'activeTime' },
        },
        {
            title: '最后修改时间',
            width: window.screen.width * 0.15,
            dataIndex: 'updatedAt',
            align: 'center',
        },
        {
            title: '修改人',
            dataIndex: 'updatedBy',
            align: 'center',
            width: window.screen.width * 0.1,
        },
        {
            title: '操作',
            align: 'center',
            dataIndex: 'action',
            fixed: 'right',
            width: 260,
            scopedSlots: { customRender: 'action' },
        }
    ]
    // 商品属性
    const goodsAttrColumn = [
        {
            title: '属性',
            dataIndex: 'orderNo',
            align: 'center',
        },
        {
            title: '属性值',
            dataIndex: 'orderNo',
            align: 'center',
        },
        {
            title: '供货价',
            dataIndex: 'orderNo',
            align: 'center',
        },
        {
            title: '售价',
            dataIndex: 'orderNo',
            align: 'center',
        },
        {
            title: '到手价',
            dataIndex: 'orderNo',
            align: 'center',
        },
        {
            title: '可用库存数量',
            dataIndex: 'orderNo',
            align: 'center',
        },
        {
            title: '盲盒商品件数',
            align: 'center',
            dataIndex: 'mhSlot1',
            width: 100,
            scopedSlots: { customRender: 'mhSlot1' },
        },
        {
            title: '试玩件数',
            align: 'center',
            dataIndex: 'mhSlot2',
            width: 120,
            scopedSlots: { customRender: 'mhSlot2' },
        },
        {
            title: '商品等级',
            align: 'center',
            dataIndex: 'mhSlot3',
            scopedSlots: { customRender: 'mhSlot3' },
        },
        {
            title: '操作',
            align: 'center',
            dataIndex: 'action',
            scopedSlots: { customRender: 'action' },
        },

    ]

    /** 去除类目中的空children，避免页面多渲染层级 */
    function removechild (arr) {
        if (arr.children && arr.children.length === 0) {
            delete arr.children;
        }
        if (arr.children && arr.children.length) {
            arr.children.map(item => removechild(item));
        }
        return arr;
    }

    /** 类目扁平数组，在 created() 获取类目 tree 数据进行扁平化后赋值 */
    let categorysFlatList = [];

    // 扁平数组
    function treeToList (tree) {
        let queen = [];
        const out = [];
        queen = queen.concat(JSON.parse(JSON.stringify(tree)));
        while (queen.length) {
            const first = queen.shift()
            if (first.children) {
                queen = queen.concat(first.children)
                delete first.children
            }
            out.push(first)
        }
        return out
    }

    /** 生成类目名称 */
    const createCategoryName = (categorys) => {
        return categorys.reduce((pre, cur) => {
            return (pre === '' ? '' : pre + '/') + categorysFlatList.find(categoryItem => categoryItem.categoryId === cur).categoryName;
        }, '');
    }

    moment.locale('zh-cn');
    var vm = new Vue({
        el: '#app',
        data: {
            editBtnLoading: false,
            queryTableLoading: false,
            // 选择商家下拉菜单
            merchantSelectOptions: [],
            locales,
            /** 展示 table 页面 */
            showTablePage: true,
            /** 搜索栏样式配置 */
            layout: {
                labelCol: { span: 7 },
                wrapperCol: { span: 17 },
            },
            /** 搜索栏数据 */
            searchForm: {},
            /** 表格数据 */
            tableData: [],
            /** 表格分页数据查询中标识位 */
            loading: false,
            /** 分页器 */
            pagination: {
                showSizeChanger: true,
                showQuickJumper: true,
                total: null,
                pageSize: 10,
                current: 1,
                showTotal: (total, range) => `共${total}条`,
                pageSizeOptions: ['10', '25', '50', '100'],
                buildOptionText: (size) => {
                    return `${size.value}条/页`
                }
            },

            tableScroll: { x: window.screen.width * 0.76, },
            dialogGoodsInfoTemplate: {
                // 商品编码
                spuId: '',
                // 商品主标题
                commodityMainTitle: '',
                // 一级类目id
                categoryIdOne: '',
                // 二级类目id
                categoryIdTwo: '',
                // 三级类目id
                categoryIdThree: '',
                // 品牌名称
                brandName: '',
                // 商户信息
                merchantVo: {
                    // 商家id
                    // merchantId: '',
                    // 商家名称
                    merchantName: ''
                },
                // 商品数据表格配置
                tableRowList: [],
                // 商品数据表格配置 模版
                tableRowListTemplate: {},
                attrs: [],
                // 商品数据表格配置 数据
                tableDataList: [],
                // 改商品的商户列表
                merchantSelectOptions: []
            },
            dialogForm: {
                // 商品信息
                blindBoxCommodityInfoVOList: [],
                // 盲盒信息
                blindBoxVO: {},
                // 价格信息
                priceVO: {},
                // 商品图片信息
                commodityPictureVos: [],

                // 主图照片列表
                mainPhotoImgList: [],
            },
            dialogFormDisable: false,
            isEdit: false,
            dialogFormRules: {
                spuId: [{ required: true, message: '请输入商品编码!', trigger: 'blur' }],
                commodityMainTitle: [{ required: true, message: '请输入!' }],
                merchantId: [{ required: true, message: '请选择商家!', trigger: 'change' }],
                attributeValueId: [{ required: true, message: '请选择商品属性值!', trigger: 'change' }],
                commodityStock: [
                    { required: true, message: '请填写!' },
                    {
                        required: true,
                        validator: commodityStockValidator
                    }
                ],
                returnRatio: [
                    { required: true, message: '请填写!' },
                    {
                        required: true,
                        validator: returnRatioValidator
                    }
                ],
                demoStock: [{ required: true, message: '请填写!' },],
                commodityGrade: [{ required: true, message: '请选择!', trigger: 'change' }],
                blindBoxName: [{ required: true, message: '请输入盲盒标题!', trigger: 'blur' }],
                blindBoxSort: [{ required: true, message: '请设置盲盒排序!', trigger: 'blur' }],
                blindBoxActiveTime: [{ type: 'array', required: true, message: '请设置活动日期!', trigger: 'change' },],
                blindBoxTag: [{ type: 'array', required: true, message: '请设置盲盒标签!', trigger: 'change' },],
                mainPhotoImgList: [{ type: 'array', required: true, message: '请上传盲盒图片!', trigger: 'change' },],
                onceOriginalPrice: [{ required: true, message: '请填写单抽原价!' }],
                continuousOriginalPrice: [{ required: false, message: '请填写N开不重原价!' }],
                continuousNum: [{ required: false, message: '请填写!' }],
                onceDiscountsPrice: [{ required: false, message: '请填写单抽限时优惠价!' }],
                continuousDiscountsPrice: [{ required: false, message: '请填写N开不重限时优惠价!' }],
                onceFirstPrice: [{ required: false, message: '请填写单抽首单优惠价!' }],
            }
        },
        watch: {

        },
        methods: {
            onChangeBilndBoxName(){
              this.dialogForm.blindBoxVO.blindBoxName = this.dialogForm.blindBoxVO.blindBoxName.replace(/\&/g, '')
            },
            disabledStartDate (startValue) {
                var date = new Date(); //获取当前Date对象
                //var date = new Date('2020/10/10 11:22:33'); //获取指定时间的Date对象，这里只能用"2020/10/10"格式，其他格式如"2020-10-10"浏览器兼容性不好
                date.setHours(0);
                date.setMinutes(0);
                date.setSeconds(0);
                date.setMilliseconds(0)
                //获取毫秒时间戳，（1970-01-01 00:00:00到现在的毫秒数）
                var timestamp = date.getTime(); // 1477670400000
                //获取unix时间戳，（1970-01-01 00:00:00到现在的秒数）
                var unix_timestamp = Math.floor(date.getTime()); //1477670400
                return startValue.valueOf() <= unix_timestamp
            },
            // 查询商品信息
            async dialogSupIdClick (index) {
                const blindBoxCommodityInfoVO = this.dialogForm.blindBoxCommodityInfoVOList[index]
                let spuIdArr = []
                for (let i = 0; i < this.dialogForm.blindBoxCommodityInfoVOList.length; i++) {
                    spuIdArr.push(this.dialogForm.blindBoxCommodityInfoVOList[i].spuId)
                }
                let idx = spuIdArr.indexOf(blindBoxCommodityInfoVO.spuId)
                let num = 0
                while (idx !== -1) {
                    num++
                    idx = spuIdArr.indexOf(blindBoxCommodityInfoVO.spuId, idx + 1)
                }
                console.log('总共出现的次数为' + num);
                if (num > 1) {
                    return this.$message.error('一件商品不能配置多次！');
                }
                if (!blindBoxCommodityInfoVO.spuId) {
                    return this.$message.error('请检查商品编码');
                }
                const url = apiUrlConfig.activityCommodityQueryForSpuId
                const params = {
                    spuId: blindBoxCommodityInfoVO.spuId,
                }
                this.$set(this.dialogForm.blindBoxCommodityInfoVOList[index], "attrVos", [])
                const { success, result, errorMsg } = await http.post(url, params);
                if (!success) {
                    this.$message.error(errorMsg);
                    return;
                }
                if (!result.commodityMainTitle) {
                    return this.$message.error('请检查商品编码');
                }
                // blindBoxCommodityInfoVO
                blindBoxCommodityInfoVO.commodityMainTitle = result.commodityMainTitle;
                blindBoxCommodityInfoVO.commoditySubtitle = result.commoditySubtitle;
                blindBoxCommodityInfoVO.brandName = result.brandName;
                blindBoxCommodityInfoVO.brandId = result.brandId;

                blindBoxCommodityInfoVO.categoryName = createCategoryName([result.categoryIdOne, result.categoryIdTwo, result.categoryIdThree]);

                blindBoxCommodityInfoVO.categoryIdOne = result.categoryIdOne
                blindBoxCommodityInfoVO.categoryIdTwo = result.categoryIdTwo
                blindBoxCommodityInfoVO.categoryIdThree = result.categoryIdThree

                blindBoxCommodityInfoVO.merchantSelectOptions = result.merchantVoList;
                if (!result.merchantVoList || result.merchantVoList.length == 0) {
                    this.$message.error('该商品暂无商户申请');
                }
                // 清空数据
                blindBoxCommodityInfoVO.merchantVo = {}
                blindBoxCommodityInfoVO.tableRowList = []
                blindBoxCommodityInfoVO.tableDataList = []
            },

            /** 商家名称选择回调 */
            async dialogMerchantNameSelect (value, index) {
                const blindBoxCommodityInfoVO = this.dialogForm.blindBoxCommodityInfoVOList[index]
                blindBoxCommodityInfoVO.merchantId = value;
                // 获取当前选中的商户
                blindBoxCommodityInfoVO.merchantSelectOptions.map(item => {
                    if (value == item.merchantId)
                        blindBoxCommodityInfoVO.merchantVo = item
                })
                // 查询属性表格和商品图片
                const url = apiUrlConfig.activitySkuQueryForMerchant
                const params = {
                    merchantId: blindBoxCommodityInfoVO.merchantId,
                    spuId: blindBoxCommodityInfoVO.spuId,
                }
                const { success, result, errorMsg } = await http.post(url, params);
                if (!success) {
                    this.$message.error(errorMsg);
                    return;
                }
                // 创建表格
                this.createdTableRowTitleList(result, index);
                console.log("result", result);
                // 把所有的行数的数据全部格式化成指定数据结构 用户选择后直接取 模版数据
                (result || []).map(item => {
                    let tempKey = []
                    item.attributeValueNameList.map(child => {
                        // 设置选中的key
                        child.selectKeys = child.attributeId + '&' + child.attributeValueId
                        tempKey.push(child.selectKeys)
                    })
                    tempKey = tempKey.join("-")
                    this.dialogForm.blindBoxCommodityInfoVOList[index].tableRowListTemplate[tempKey] = JSON.parse(JSON.stringify(item))
                })
            },
            /** 创建表格头 */
            createdTableRowTitleList (attributeVos, index) {
                const lw1 = window.screen.width * 0.08
                const lw2 = window.screen.width * 0.1
                let rowList = attributeVos[0].attributeValueNameList.map(rowItem => {
                    return {
                        title: rowItem.attributeName,
                        dataIndex: rowItem.attributeId,
                        align: 'center',
                        width: lw1,
                    }
                });
                const otherRowList = [
                    {
                        title: '供货价',
                        dataIndex: 'supplyPrice',
                        align: 'center',
                        width: lw1,
                    },
                    {
                        title: '售价',
                        dataIndex: 'sellingPrice',
                        align: 'center',
                        width: lw1,
                    },
                    {
                        title: '到手价',
                        dataIndex: 'onHandPrice',
                        align: 'center',
                        width: lw1,
                    },
                ];
                if (!this.dialogFormDisable) {
                    otherRowList.push(

                        {
                            title: '可用库存数量',
                            dataIndex: 'availableStock',
                            align: 'center',
                            width: lw2,
                        }
                    )
                }
                let rowItem = {
                    title: '盲盒商品件数',
                    dataIndex: 'mhSlot1',
                    align: 'center',
                    width: lw2,
                    scopedSlots: { customRender: 'mhSlot1' },
                }
                // !this.isEdit && !this.dialogFormDisable && (rowItem.fixed = 'right')
                otherRowList.push(rowItem)
                rowItem = {
                    title: '试玩件数',
                    dataIndex: 'mhSlot2',
                    align: 'center',
                    width: lw2,
                    scopedSlots: { customRender: 'mhSlot2' },
                }
                // !this.isEdit && !this.dialogFormDisable && (rowItem.fixed = 'right')
                otherRowList.push(rowItem)
                rowItem = {
                    title: '商品等级',
                    dataIndex: 'mhSlot3',
                    align: 'center',
                    width: lw2,
                    scopedSlots: { customRender: 'mhSlot3' },
                }
                // !this.isEdit && !this.dialogFormDisable && (rowItem.fixed = 'right')
                // otherRowList.push(rowItem)
                // rowItem = {
                //   title: '回收比例',
                //   dataIndex: 'mhSlot4',
                //   align: 'center',
                //   width: lw2,
                //   scopedSlots: { customRender: 'mhSlot4' },
                // }
                // !this.isEdit && !this.dialogFormDisable && (rowItem.fixed = 'right')
                otherRowList.push(rowItem)
                // dialogFormDisable
                otherRowList.forEach(rowItem => rowList.push(rowItem));
                if (!this.dialogFormDisable) {
                    rowList.push({
                        title: '回收比例',
                        dataIndex: 'mhSlot4',
                        align: 'center',
                        width: lw2,
                        scopedSlots: { customRender: 'mhSlot4' },
                    })
                    // 新增
                    rowList.push({
                        title: '操作',
                        dataIndex: 'action',
                        // fixed: 'right',
                        align: 'center',
                        width: lw2,
                        scopedSlots: { customRender: 'action' },
                    })
                } else {
                    // 查看
                    rowList.push({
                        title: '剩余盲盒商品数量',
                        dataIndex: 'commodityAvailableStock',
                        align: 'center',
                        width: lw2,
                        // fixed: 'right',
                    })
                    rowList.push({
                        title: '商品抽中概率',
                        dataIndex: 'probability',
                        align: 'center',
                        // fixed: 'right',
                        width: lw2,
                        scopedSlots: { customRender: 'probability' },
                    })
                    rowList.push({
                        title: '回收比例',
                        dataIndex: 'mhSlot4',
                        align: 'center',
                        width: lw2,
                        scopedSlots: { customRender: 'mhSlot4' },
                    })
                }
                this.dialogForm.blindBoxCommodityInfoVOList[index].tableRowList = rowList;
                // this.createTableData(attributeVos , index);
                this.dialogForm.blindBoxCommodityInfoVOList[index].attributeVos = attributeVos
                this.createSelectData(attributeVos, index);
            },
            /** 创建选择框数据 */
            createSelectData (attributeVos, index) {
                let attrVo = []
                // 1 获取所有的属性 及 属性值
                attributeVos.map(item => {
                    item.attributeValueNameList.map((child) => {
                        // attributeId
                        // attributeValueId
                        let isCf = false
                        // console.log("attrVo" , attrVo)
                        attrVo.map(attrVoItem => {
                            if (attrVoItem.attributeId == child.attributeId && attrVoItem.attributeValueId == child.attributeValueId) {
                                isCf = true
                            }
                        })
                        // 2. 属性和属性值去重
                        if (!isCf)
                            attrVo.push({ ...child })
                    })
                })
                console.log("attrVo", attrVo)
                // 3. 一位数组 转二维数组
                // attributeId: 父
                // attributeValueId: 子
                let _attrVos = {}
                // a.先定义一级节点
                let attrVos = []

                attrVo.map(item => {
                    if (!_attrVos[item.attributeId]) {
                        _attrVos[item.attributeId] = []
                        attrVos.push({
                            attributeId: item.attributeId,
                            attributeName: item.attributeName,
                            value: [],
                            children: {}
                        })
                    }
                })
                // b.传入二级节点 child.attributeId + '&' + child.attributeValueId
                attrVos.map((child) => {
                    attrVo.map(item => {
                        if (child.attributeId == item.attributeId) {
                            if (!child.children[item.attributeId + '&' + item.attributeValueId]) {

                                child.children[item.attributeId + '&' + item.attributeValueId] = ({
                                    ...item,
                                    children: {}
                                })
                            }
                        }
                    })
                })
                this.$set(this.dialogForm.blindBoxCommodityInfoVOList[index], "attrVos", attrVos)
            },
            dialogMerchantAttrSelect (eve, formIndex, k) {
                this.createTableData(this.dialogForm.blindBoxCommodityInfoVOList[formIndex].attributeVos, formIndex);
                // 根据选择内容 渲染不同表哥数据
            },
            diffCoumKeys (columnKeys) {
                let column = []
                let attrLen = columnKeys.length
                // 获取所有的变化
                let childKeyLen = []
                for (let i = 0; i < attrLen; i++) {
                    childKeyLen[i] = columnKeys[i].length
                }
                function getColumnKArr (childKey, index = 0, k) {
                    // 没有数据直接停止执行
                    for (let i = 0; i < childKey[index]; i++) {
                        k[index] = i
                        if (attrLen == k.length)
                            column.push([...k])
                        if (childKey[index + 1]) {
                            k[index + 1] = 0
                            getColumnKArr(childKey, index + 1, k)
                        }
                    }
                }
                // 获取到可能的数组情况
                getColumnKArr(childKeyLen, 0, [0])
                let returnKey = {}
                column.map(child => {
                    let krr = []
                    child.map((i, j) => {
                        krr.push(columnKeys[j][i])
                    })
                    const okey = krr.join("-")
                    returnKey[okey] = ''
                })
                return Object.keys(returnKey)
            },
            /** 创建表格数据 */
            createTableData (attributeVos, index) {

                const tableDataList = []
                // 当前商品下的所有 属性数据
                const myAttrVos = JSON.parse(JSON.stringify(this.dialogForm.blindBoxCommodityInfoVOList[index].attrVos))
                // 获取所有商品属性数据模版
                const tableRowListTemplate = JSON.parse(JSON.stringify(this.dialogForm.blindBoxCommodityInfoVOList[index].tableRowListTemplate));
                // 获取数据行数，通过命中了哪些属性判断
                // 将选项 的数据key值 转成 二维数组结构
                let columnKeys = []
                myAttrVos.map((item, index) => {
                    columnKeys[index] = []
                    if (item.value && item.value.length > 0) {
                        columnKeys[index] = item.value
                    }
                })
                // 获取 所需模版的 key
                let columns = this.diffCoumKeys(columnKeys)
                let column = []
                function getAllCompose (source, count, isPermutation = true) {
                    //如果只取一位，返回数组中的所有项，例如 [ [1], [2], [3] ]
                    let currentList = source.map((item) => [item]);
                    if (count === 1) {
                        return currentList;
                    }
                    let result = [];
                    //取出第一项后，再取出后面count - 1 项的排列组合，并把第一项的所有可能（currentList）和 后面count-1项所有可能交叉组合
                    for (let i = 0; i < currentList.length; i++) {
                        let current = currentList[i];
                        //如果是排列的方式，在取count-1时，源数组中排除当前项
                        let children = [];
                        if (isPermutation) {
                            children = getAllCompose(source.filter(item => item !== current[0]), count - 1, isPermutation);
                        }
                        //如果是组合的方法，在取count-1时，源数组只使用当前项之后的
                        else {
                            children = getAllCompose(source.slice(i + 1), count - 1, isPermutation);
                        }
                        for (let child of children) {
                            result.push([...current, ...child]);
                        }
                    }
                    return result;
                }
                // 重铸 key 使用 tableRowListTemplate里面的key 替换
                const tableRowListTemplateKey = Object.keys(tableRowListTemplate)
                columns.map(columnKey => {
                    let columnKey1 = columnKey.split("-")
                    let _allColumnKey = getAllCompose(columnKey1, columnKey1.length)
                    let allColumnKey = []
                    _allColumnKey.map(item => {
                        allColumnKey.push(item.join("-"))
                    })
                    tableRowListTemplateKey.map(key => {

                        if (allColumnKey.indexOf(key) != -1) {
                            column.push(key)
                        }
                    })
                })
                // column
                console.log("column", column)
                const firstAttrValueList = attributeVos[0].attributeValueNameList;
                // 遍历所有的行数，找出每种的属性值, 把table的数据也一块生成，不然还得第二次遍历
                for (let i = 0; i < column.length; i++) {
                    // 当前行的 所有数据
                    const attributeVosI = tableRowListTemplate[column[i]];
                    // 遍历每一行都先给table添加一行数据, attributeValueNameList 数组用于存储列属性数据，方便提交时组装数据。
                    tableDataList.push({ attributeValueNameList: [] });
                    // 遍历每一列的数据。列数是固定的
                    for (let j = 0; j < firstAttrValueList.length; j++) {
                        // 获取当前行当前列 获取到的 value
                        const valueItem = attributeVosI.attributeValueNameList[j];
                        // 填充每一行table数据的列
                        tableDataList[i][valueItem.attributeId] = valueItem.attributeValueName;
                        // 将属性的相关内容
                        tableDataList[i].attributeValueNameList.push({
                            attributeId: valueItem.attributeId,
                            attributeName: valueItem.attributeName,
                            attributeValueName: valueItem.attributeValueName,
                            attributeValueId: valueItem.attributeValueId,
                        });
                    }
                    tableDataList[i].skuId = attributeVosI.skuId;
                    tableDataList[i].supplyPrice = Number(attributeVosI.supplyPrice || 0) / 100;
                    tableDataList[i].sellingPrice = Number(attributeVosI.sellingPrice || 0) / 100;
                    tableDataList[i].onHandPrice = Number(attributeVosI.onHandPrice || 0) / 100;
                    if (!attributeVosI.activityPrice && attributeVosI.activityPrice !== 0) {
                        tableDataList[i].activityPrice = '';
                    } else {
                        tableDataList[i].activityPrice = Number(attributeVosI.activityPrice) / 100;
                    }
                    tableDataList[i].availableStock = attributeVosI.availableStock;
                    tableDataList[i].activityAvailableStock = attributeVosI.activityAvailableStock;
                    tableDataList[i].activityStock = attributeVosI.activityStock;
                    tableDataList[i].limitNumber = attributeVosI.limitNumber;
                    tableDataList[i].key = attributeVosI.skuId;
                    tableDataList[i].activityPriceError = false;
                    // 盲盒商品库存
                    tableDataList[i].commodityStock = '';
                    // 盲盒商品可用库存
                    tableDataList[i].commodityAvailableStock = attributeVosI.availableStock;
                    // 盲盒试玩库存
                    tableDataList[i].demoStock = '';
                    // 盲盒回收比例
                    tableDataList[i].returnRatio = '';

                    // returnRatio: child.returnRatio
                    // 盲盒商品等级
                    // tableDataList[i].commodityGrade = null;

                };
                // this.dialogForm.blindBoxCommodityInfoVOList[index].tableDataList = tableDataList ;
                this.$set(this.dialogForm.blindBoxCommodityInfoVOList[index], "tableDataList", tableDataList)
            },

            // 添加商品
            onAddGoodsForm (formIndex) {
                this.dialogForm.blindBoxCommodityInfoVOList.splice(formIndex + 1, 0, JSON.parse(JSON.stringify(this.dialogGoodsInfoTemplate)))
                this.$message.success('添加成功');
            },
            // 删除商品
            onDelGoodsForm (formIndex) {
                const _this = this
                this.$confirm({
                    title: '删除',
                    content: '确认删除？',
                    okText: '确定',
                    okType: 'danger',
                    cancelText: '取消',
                    onOk () {
                        console.log('OK');
                        _this.dialogForm.blindBoxCommodityInfoVOList.splice(formIndex, 1)
                        _this.$message.success('删除成功');
                    },
                    onCancel () {
                        console.log('Cancel');
                    },
                });
            },
            // 删除表单中商品属性
            removeAttrs (record, index, formIndex) {
                console.log("removeAttrs", { record, index, formIndex })
                const _this = this
                this.$confirm({
                    title: '删除',
                    content: '确认删除？',
                    okText: '确定',
                    okType: 'danger',
                    cancelText: '取消',
                    onOk () {
                        console.log('OK');
                        _this.dialogForm.blindBoxCommodityInfoVOList[formIndex].tableDataList.splice(index, 1)
                        if (_this.dialogForm.blindBoxCommodityInfoVOList[formIndex].tableDataList.length == 0) {
                            _this.dialogForm.blindBoxCommodityInfoVOList[formIndex].attrVos.map(item => {
                                item.value = []
                            })
                        }
                    },
                    onCancel () {
                        console.log('Cancel');
                    },
                });
            },
            async getBlindBoxDetail (value) {
                // 编辑
                // blindBoxDetailQuery
                // 通过接口查询已配置商品信息
                const url = apiUrlConfig.blindBoxDetailQuery;
                const params = {
                    id: value.id,
                    blindBoxId: value.blindBoxId,
                };
                this.editBtnLoading = true
                const { success, result, errorMsg } = await http.post(url, params);
                if (!success) {

                    this.editBtnLoading = false
                    this.$message.error(errorMsg);
                    return;
                }
                // console.log(this.tableData,value)
                // 把接口拿到的数据 渲染页面， 代码冗余逻辑
                const mhDetail = JSON.parse(JSON.stringify(result))
                let dialogForm = {}
                dialogForm.blindBoxCommodityInfoVOList = []
                mhDetail.blindBoxCommodityInfoVOList.map((item, index) => {
                    let itemOpt = JSON.parse(JSON.stringify(this.dialogGoodsInfoTemplate))
                    // spuId 商品编码(商品id)
                    itemOpt.spuId = item.spuId
                    // 商品主标题
                    itemOpt.commodityMainTitle = item.commodityMainTitle
                    // 一级类目id
                    itemOpt.categoryIdOne = item.categoryIdOne
                    // 二级类目id
                    itemOpt.categoryIdTwo = item.categoryIdTwo
                    // 三级类目id
                    itemOpt.categoryIdThree = item.categoryIdThree
                    // 品牌名称
                    itemOpt.brandName = item.brandName
                    // 商户信息
                    itemOpt.merchantVo = {
                        merchantId: item.merchantVo.merchantId,
                        merchantName: item.merchantVo.merchantName,
                    }
                    /**表格数据 */
                    itemOpt.BlindBoxSkuVOList = JSON.parse(JSON.stringify(item.blindBoxSkuVOList))
                    itemOpt.tableDataList = []
                    dialogForm.blindBoxCommodityInfoVOList.push(itemOpt)
                })
                /** 盲盒信息 */
                const blindBoxVO = mhDetail.blindBoxVO
                dialogForm.blindBoxVO = {}
                dialogForm.mainPhotoImgList = mhDetail.commodityPictureVos || []
                // 盲盒名称
                dialogForm.blindBoxVO.blindBoxName = blindBoxVO.blindBoxName
                // 活动时间
                dialogForm.blindBoxVO.blindBoxActiveTime = [
                    moment(blindBoxVO.blindBoxStartTime),
                    moment(blindBoxVO.blindBoxEndTime)
                ]
                let _blindBoxTag = blindBoxVO.blindBoxTag.replace(/@@/g, "\\"); //反斜杠转换为@@
                    _blindBoxTag = _blindBoxTag.replace(/--$/g, "\\"); //$符转换为--
                    _blindBoxTag = _blindBoxTag.replace(/\^\^/g, "|"); //竖杠转换为^^
                    _blindBoxTag = _blindBoxTag.replace(/!!/g, "%");  //%转换为!!
                    _blindBoxTag = _blindBoxTag.replace(/==/g, "\""); //双引号转换为==
                    _blindBoxTag = _blindBoxTag.replace(/\*\*/g, "\'"); 
                // 盲盒标签
                try {
                  dialogForm.blindBoxVO.blindBoxTag = atobBtoaUtils.atob(_blindBoxTag).split(" ")
                } catch (error) {
                  // 解码报错 默认为 旧版本数据问题 不需要解码
                  console.log(error)

                  dialogForm.blindBoxVO.blindBoxTag = (blindBoxVO.blindBoxTag.split(" ")) 
                }
                // !!-!!
                
                // 盲盒排序
                dialogForm.blindBoxVO.blindBoxSort = blindBoxVO.blindBoxSort
                /** 价格信息 */
                const priceVO = mhDetail.priceVO
                dialogForm.priceVO = {}
                // 单抽原价，单位分
                dialogForm.priceVO.onceOriginalPrice = floatObj.divide(priceVO.onceOriginalPrice, 100, 2)
                // 单抽限时优惠价，单位分 onceDiscountsPrice
                dialogForm.priceVO.onceDiscountsPrice = floatObj.divide(priceVO.onceDiscountsPrice, 100, 2)
                // 单抽首单优惠价，单位分
                dialogForm.priceVO.onceFirstPrice = floatObj.divide(priceVO.onceFirstPrice, 100, 2)
                // N连抽不重复数量
                dialogForm.priceVO.continuousNum = priceVO.continuousNum
                // N连抽不重复原价，单位分 continuousOriginalPrice
                dialogForm.priceVO.continuousOriginalPrice = floatObj.divide(priceVO.continuousOriginalPrice, 100, 2)
                // N连抽不重复限时优惠价，单位分
                dialogForm.priceVO.continuousDiscountsPrice = floatObj.divide(priceVO.continuousDiscountsPrice, 100, 2)
                this.dialogForm = JSON.parse(JSON.stringify(dialogForm))
                console.log("....this.dialogForm....", this.dialogForm)
                // 从接口获取商品信息数据
                dialogForm.blindBoxCommodityInfoVOList.map(async (item, index) => {
                    // 获取商品信息
                    await this.dialogSupIdClick(index)
                    // 设置商家
                    await this.dialogMerchantNameSelect(item.merchantVo.merchantId, index)

                    this.editBtnLoading = false
                    // 设置商品选中的属性值
                    let skuIds = []
                    // 获取所有的 skuId
                    item.BlindBoxSkuVOList.map(child => {
                        skuIds.push(child.skuId)
                    })
                    console.log("skuIds", skuIds)
                    const tableRowListTemplate = this.dialogForm.blindBoxCommodityInfoVOList[index].tableRowListTemplate
                    // 找到  tableRowListTemplateKey 渲染表格
                    let tableRowListTemplateKeys = []
                    // 通过 sku 获取当前选中的属性
                    let skuIdObj = {}
                    Object.keys(tableRowListTemplate).map(key => {
                        if (skuIds.indexOf(tableRowListTemplate[key].skuId) != -1) {
                            tableRowListTemplateKeys.push(key)
                            tableRowListTemplate[key].attributeValueNameList.map(itm => {
                                if (!skuIdObj[itm.attributeId])
                                    skuIdObj[itm.attributeId] = []
                                if (skuIdObj[itm.attributeId].indexOf(itm.selectKeys) == -1)
                                    skuIdObj[itm.attributeId].push(itm.selectKeys)
                            })
                            // skuIdObj
                        }
                    })
                    const attrVos = this.dialogForm.blindBoxCommodityInfoVOList[index].attrVos
                    // 把sku 初始数据 渲染到页面
                    attrVos.map(aitm => {
                        if (skuIdObj[aitm.attributeId]) {
                            aitm.value = skuIdObj[aitm.attributeId]
                        }
                    })
                    console.log("tableRowListTemplateKeys", tableRowListTemplateKeys)
                    // 把模版数据 渲染到表格页面
                    this.dialogMerchantAttrSelect('', index, '')

                    const tableDataList = this.dialogForm.blindBoxCommodityInfoVOList[index].tableDataList
                    const commodityGradeObj = {
                        first: '1',
                        second: '2',
                    }
                    // 把接口数据 填充到 表格中
                    tableDataList.map((tbitm, tindex) => {
                        item.BlindBoxSkuVOList.map(itm => {
                            if (tbitm.skuId == itm.skuId) {
                                tbitm = {
                                    ...tbitm,
                                    ...itm,
                                    commodityGrade: commodityGradeObj[itm.commodityGrade],
                                    supplyPrice: floatObj.divide(itm.supplyPrice, 100, 2),
                                    sellingPrice: floatObj.divide(itm.sellingPrice, 100, 2),
                                    onHandPrice: floatObj.divide(itm.onHandPrice, 100, 2),
                                }

                                this.$set(this.dialogForm.blindBoxCommodityInfoVOList[index].tableDataList, tindex, tbitm)
                            }
                        })
                    })
                    this.dialogForm.blindBoxId = value.blindBoxId
                })
            },
            async showDetailDialog (value) {
                this.isEdit = false
                this.dialogFormDisable = true
                this.getBlindBoxDetail(value)
                this.showTablePage = false
            },
            // 上架 下架
            async onblindBoxSoldOut (value) {
                const effectiveN = {
                    "TRUE": 0,
                    "FALSE": 1
                }
                const url = apiUrlConfig.blindBoxSoldOut;
                const params = {
                    id: value.id,
                    blindBoxId: value.blindBoxId,
                    effective: effectiveN[value.effective]
                };
                const { success, result, errorMsg } = await http.post(url, params);
                if (!success) {
                    this.$message.error(errorMsg);
                    return;
                }
                this.$message.success("操作成功");

                this.queryTableData()
            },
            // add  update
            async onSetShowTablePage (value) {
                this.isEdit = true
                this.dialogFormDisable = true
                if (!value) {
                    this.dialogFormDisable = false
                    this.isEdit = false
                    this.dialogForm.blindBoxCommodityInfoVOList = [JSON.parse(JSON.stringify(this.dialogGoodsInfoTemplate))]
                }
                else
                    this.getBlindBoxDetail(value)
                this.showTablePage = false
            },
            getXhrOptions () {
                console.log('submit! 表单信息，格式化数据给接口');
                console.log(this.dialogForm)
                let options = {}
                options.blindBoxCommodityInfoVOList = []
                // 商品信息
                this.dialogForm.blindBoxCommodityInfoVOList.map((item, index) => {
                    let itemOpt = {}
                    // spuId 商品编码(商品id)
                    itemOpt.spuId = item.spuId
                    // 商品主标题
                    itemOpt.commodityMainTitle = item.commodityMainTitle
                    // 一级类目id
                    itemOpt.categoryIdOne = item.categoryIdOne
                    // 二级类目id
                    itemOpt.categoryIdTwo = item.categoryIdTwo
                    // 三级类目id
                    itemOpt.categoryIdThree = item.categoryIdThree
                    // 品牌名称
                    itemOpt.brandName = item.brandName
                    // 商户信息
                    itemOpt.merchantVo = {
                        merchantId: item.merchantVo.merchantId,
                        merchantName: item.merchantVo.merchantName,
                    }
                    // 商品属性信息
                    itemOpt.BlindBoxSkuVOList = []
                    item.tableDataList.map(child => {
                        itemOpt.BlindBoxSkuVOList.push({
                            // 商品规格id
                            skuId: child.skuId,
                            // 供货价
                            supplyPrice: floatObj.multiply(child.supplyPrice, 100, 0),
                            // 售价
                            sellingPrice: floatObj.multiply(child.sellingPrice, 100, 0),
                            // 到手价
                            onHandPrice: floatObj.multiply(child.onHandPrice, 100, 0),
                            // 盲盒商品库存
                            commodityStock: child.commodityStock,
                            // 盲盒商品可用库存
                            commodityAvailableStock: child.commodityAvailableStock,
                            // 试玩库存
                            demoStock: child.demoStock,
                            // 商品等级
                            commodityGrade: Number(child.commodityGrade),
                            // 回收比例
                            returnRatio: child.returnRatio
                        })
                    })
                    options.blindBoxCommodityInfoVOList.push(itemOpt)
                })
                const blindBoxVO = this.dialogForm.blindBoxVO
                /** 盲盒信息 */
                options.blindBoxVO = {}
                // 盲盒名称
                options.blindBoxVO.blindBoxName = blindBoxVO.blindBoxName
                // 开始时间 blindBoxActiveTime
                console.log('blindBoxVO.blindBoxActiveTime', blindBoxVO.blindBoxActiveTime)
                options.blindBoxVO.blindBoxStartTime = (blindBoxVO.blindBoxActiveTime && blindBoxVO.blindBoxActiveTime[0]) && moment(blindBoxVO.blindBoxActiveTime[0]).format('YYYY-MM-DD') + ' 00:00:00'
                // 结束时间
                options.blindBoxVO.blindBoxEndTime = (blindBoxVO.blindBoxActiveTime && blindBoxVO.blindBoxActiveTime[1]) && moment(blindBoxVO.blindBoxActiveTime[1]).format('YYYY-MM-DD') + " 23:59:59"
                // 盲盒标签
                console.log("blindBoxVO.blindBoxTag" , blindBoxVO.blindBoxTag)
                options.blindBoxVO.blindBoxTag = atobBtoaUtils.btoa(blindBoxVO.blindBoxTag.join(" ")) 
                // 盲盒排序
                options.blindBoxVO.blindBoxSort = blindBoxVO.blindBoxSort
                /** 价格信息 */
                const priceVO = this.dialogForm.priceVO
                options.priceVO = {}
                // 单抽原价，单位分
                options.priceVO.onceOriginalPrice = floatObj.multiply(priceVO.onceOriginalPrice, 100, 0)
                // 单抽限时优惠价，单位分 onceDiscountsPrice
                options.priceVO.onceDiscountsPrice = priceVO.onceDiscountsPrice && floatObj.multiply(priceVO.onceDiscountsPrice, 100, 0)
                // 单抽首单优惠价，单位分
                options.priceVO.onceFirstPrice = priceVO.onceFirstPrice && floatObj.multiply(priceVO.onceFirstPrice, 100, 0)
                // N连抽不重复数量
                options.priceVO.continuousNum = priceVO.continuousNum
                // N连抽不重复原价，单位分 continuousOriginalPrice
                options.priceVO.continuousOriginalPrice = priceVO.continuousOriginalPrice && floatObj.multiply(priceVO.continuousOriginalPrice, 100, 0)
                // N连抽不重复限时优惠价，单位分
                options.priceVO.continuousDiscountsPrice = priceVO.continuousDiscountsPrice && floatObj.multiply(priceVO.continuousDiscountsPrice, 100, 0)
                console.log("接口接受的数据", JSON.parse(JSON.stringify(options)))


                this.editBtnLoading = true
                options.commodityPictureVos = this.dialogForm.mainPhotoImgList
                return options
            },
            async onSubmitXhr () {

                const url = !this.isEdit ? apiUrlConfig.blindBoxAdd : apiUrlConfig.blindBoxModify
                const options = this.getXhrOptions()
                var params = {}
                if (this.isEdit) {

                    // let blindBoxName = newValue.replace(/(^\s*)|(\s*$)/g, "")
                    // blindBoxName = blindBoxName.replace(/[\r\n\t]/g,"")
                    // this.searchForm.blindBoxName = blindBoxName

                    params.blindBoxId = this.dialogForm.blindBoxId
                    params.blindBoxName = options.blindBoxVO.blindBoxName
                    params.blindBoxName = params.blindBoxName.replace(/(^\s*)|(\s*$)/g, "")
                    params.blindBoxName = params.blindBoxName.replace(/[\r\n\t]/g, "")
                    params.blindBoxTag = options.blindBoxVO.blindBoxTag
                    params.blindBoxSort = options.blindBoxVO.blindBoxSort

                    for (let key in options) {
                        if (typeof options[key] === 'object') {
                            options[key] = JSON.stringify(options[key]);
                        }
                    }
                    params.commodityPictureVos = options.commodityPictureVos
                } else {
                    for (let key in options) {
                        if (typeof options[key] === 'object') {
                            options[key] = JSON.stringify(options[key]);
                        }
                    }
                    params = options
                }
                var { success, result, errorMsg } = await http.post(url, params);
                this.editBtnLoading = false
                if (!success) {
                    this.$message.error(errorMsg);
                    return;
                }
                this.$message.success(!this.isEdit ? "添加成功！" : "修改成功");

                this.clearDialogForm()
                this.showTablePage = true
                this.queryTableData()
            },
            clearDialogForm () {
                this.dialogForm = {
                    // 商品信息
                    blindBoxCommodityInfoVOList: [],
                    // 盲盒信息
                    blindBoxVO: {},
                    // 价格信息
                    priceVO: {},
                    // 商品图片信息
                    commodityPictureVos: [],

                    // 主图照片列表
                    mainPhotoImgList: [],
                }
            },
            // 提交表单
            onSubmit (type) {
                if (type == false) {
                    this.showTablePage = true
                    this.clearDialogForm()
                    return
                }
                // this.isEdit
                if (this.isEdit) {
                    // 编辑 只校验 标题 排序 和 标签 图片
                    let validErrorCount = 0
                    this.$refs.ruleForm.validateField(["blindBoxVO.blindBoxName", 'blindBoxVO.blindBoxSort', 'blindBoxVO.blindBoxTag', 'mainPhotoImgList'], valid => {
                        if (!valid) {
                        } else {
                            validErrorCount++
                            console.log('error submit!!', valid);
                            return false;
                        }
                    });
                    setTimeout(() => {

                        if (validErrorCount == 0) {
                            this.onSubmitXhr()
                        }
                    }, 300)
                } else {

                    // 新增全部校验
                    this.$refs.ruleForm.validate(async valid => {
                        if (valid) {
                            this.onSubmitXhr()
                        } else {
                            console.log('error submit!!', valid);

                            this.$message.error("表单校验出错，请校验表单");
                            return false;
                        }
                    });
                }


            },
            // 盲盒时间切换 主动娇艳
            onBlindBoxActiveTimeChange () {
                this.$refs.ruleForm.validateField(['blindBoxVO.blindBoxActiveTime'], valid => { });
            },
            // 盲盒标签筛选
            onBlindBoxTagChange (value) {
                let blindBoxTag = []
                value.map(item => {
                    let a = item.split(",")
                    blindBoxTag = [...blindBoxTag, ...a]
                })
                // 去重
                let blindBoxTagObj = {}
                blindBoxTag.map(function (s) {
                    if (s && s.trim()) {
                        blindBoxTagObj[s] = ''
                    }
                });
                this.dialogForm.blindBoxVO.blindBoxTag = Object.keys(blindBoxTagObj)
            },
            onQueryTableData () {
                this.pagination.current = 1
                this.queryTableData()

            },
            // 获取盲盒活动列表
            async queryTableData () {
                // let searchForm =
                delete this.searchForm.blindBoxStartTime
                delete this.searchForm.blindBoxEndTime
                if (this.searchForm.blindBoxTime && this.searchForm.blindBoxTime.length > 0) {
                    this.searchForm.blindBoxStartTime = (moment(this.searchForm.blindBoxTime[0]).format('YYYY-MM-DD')) + ' 00:00:00'
                    this.searchForm.blindBoxEndTime = (moment(this.searchForm.blindBoxTime[1]).format('YYYY-MM-DD')) + " 23:59:59"
                }

                const options = {
                    ...this.searchForm,
                    size: this.pagination.pageSize,
                    current: this.pagination.current,
                }
                this.queryTableLoading = true
                console.log("this.searchForm", options)
                const url = apiUrlConfig.queryList;
                if (options.blindBoxName) {
                    options.blindBoxName = options.blindBoxName.replace(/(^\s*)|(\s*$)/g, "")
                    options.blindBoxName = options.blindBoxName.replace(/[\r\n\t]/g, "")
                }
                if (!options.blindBoxName) {
                    delete options.blindBoxName
                }
                if (!options.blindBoxId) {
                    delete options.blindBoxId
                }
                if (!options.blindBoxStatus) {
                    delete options.blindBoxStatus
                }
                if (!options.effective) {
                    delete options.effective
                }

                const { success, result, errorMsg } = await http.post(url, options);
                this.queryTableLoading = false
                if (!success) {
                    this.$message.error(errorMsg);
                    return;
                }
                this.pagination.total = result.total;
                this.tableData = result.records;
            },
            /** 分页器事件处理 */
            handleTableChange (pagination) {
                // 设置分页器数据
                this.$set(this, 'pagination', pagination);
                // 查询 table 数据
                this.queryTableData();
            },
            /** 弹窗按钮点击处理 */
            async dialogButtonClick (auditStatus) {
                if (auditStatus === 'CANCEL') {
                    this.showTablePage = true;
                    setTimeout(() => {
                        window.scrollTo(0, 0);
                    }, 400);
                    return;
                }
            },
            /** 重置搜索查询条件 */
            resetSearchFormInfo () {
                this.searchForm = {};
                console.log('重置搜索查询条件');
            },
            // 添加商品数据
            addBlindBoxCommodityInfoVOList (index) {
                this.$set(this.dialogForm.blindBoxCommodityInfoVOList, index, [JSON.parse(JSON.stringify(this.dialogGoodsInfoTemplate))])
            },
            dragover (e) {
                e.preventDefault();
            },
            dragenter (e, index, type) {
                e.preventDefault();
                // 避免源对象触发自身的dragenter事件
                if (this.dragIndex !== index) {
                    const list = this.dialogForm[`${type}PhotoImgList`];
                    const source = list[this.dragIndex];
                    list.splice(this.dragIndex, 1);
                    list.splice(index, 0, source);
                    // 排序变化后目标对象的索引变成源对象的索引
                    this.dragIndex = index;
                }
            },
            /** 上传照片处理 */
            photoInputChange (type) {
                const reader = new FileReader();
                console.log(type)
                const file = this.$refs[`${type}PhotoInput`].files[0];
                if (!file) {
                    return;
                }

                reader.readAsDataURL(file);
                reader.onload = async (e) => {
                    const url = '/PF/service/fastDfsServer/upload.upload';
                    const form = new FormData();
                    form.append('file', file);
                    form.append('attachPath1', file.name.split('.')[1]);

                    // 调用图片上传接口
                    const res = await axios.post(url, form).finally(() => {
                        this.$refs[`${type}PhotoInput`].value = '';
                    });
                    const { success, result, errorMsg } = JSON.parse(res.data);
                    console.log(result, '图片上传接口');
                    if (!success) {
                        this.$message.error(errorMsg);
                        return;
                    }
                    this.dialogForm[`${type}PhotoImgList`]= [{
                        pictureUrl: result.fileUrl,
                        fileGroup: result.fileGroup,
                        fileName: result.fileName,
                    }];

                    this.$refs.ruleForm.validateField(['mainPhotoImgList'], valid => { });
                }
            },
            /** 删除照片 */
            async photoDelete (index, type) {
                const name = `${type}PhotoImgList`;
                const url = '/PF/service/fastDfsServer/delete.do';
                const params = {
                    fileGroup: this.dialogForm[name][index].fileGroup,
                    fileName: this.dialogForm[name][index].fileName,
                };
                // 调用图片删除接口
                console.log(params, '删除图片参数');
                const { success, result, errorMsg } = await http.post(url, params);
                console.log(result, '图片删除接口');
                if (!success) {
                    this.$message.error(errorMsg);
                    return;
                }
                if (result) {
                    this.dialogForm[name].splice(index, 1);
                }
                    this.$refs.ruleForm.validateField(['mainPhotoImgList'], valid => { });
            },
            /** 照片拖拽排序 */
            dragstart (index) {
                this.dragIndex = index;
            },
        },
        computed: {
            // 稀有款
            xyprobability () {
                let znum = 0
                let num = 0
                this.dialogForm.blindBoxCommodityInfoVOList.map((item, index) => {
                    (item.tableDataList || []).map(child => {
                        znum += child.commodityStock || 0
                        if (child.commodityGrade == 1) {
                            num += child.commodityStock || 0
                        }
                    })
                })
                return (znum ? (floatObj.multiply(floatObj.divide(num, znum, 4) || 0, 100, 2) || '0.00') : '0.00') + '%'
            },
            // 普通
            ptprobability () {
                let znum = 0
                let num = 0
                this.dialogForm.blindBoxCommodityInfoVOList.map((item, index) => {
                    (item.tableDataList || []).map(child => {
                        znum += child.commodityStock || 0
                        if (child.commodityGrade == 2) {
                            num += child.commodityStock || 0
                        }
                    })
                })
                return (znum ? (floatObj.multiply(floatObj.divide(num, znum, 4) || 0, 100, 2) || '0.00') : '0.00') + '%'
            },

        },
        async created () {
            this.addBlindBoxCommodityInfoVOList(0)

            const categoryUrl = apiUrlConfig.categoryUrl;
            const { success: categorySuccess, result: categoryResult, errorMsg: categoryErrorMsg } = await http.post(categoryUrl, {});
            console.log(categoryResult, '查询类目列表')
            if (!categorySuccess) {
                this.$message.error(categoryErrorMsg);
                return;
            }
            this.categorys = categoryResult.commodityCategoryVoList.map(item => removechild(item));
            // 扁平化类目数据，方便表格类目名称渲染
            categorysFlatList = treeToList(categoryResult.commodityCategoryVoList);

        },
        mounted () {
            this.queryTableData()
        }
    });
    // 盲盒商品件数校验
    function commodityStockValidator (rule, value, cb) {
        let fields = rule.field.split('.')
        fields.pop()
        let availableStock = vm.dialogForm
        fields.map(key => {
            availableStock = availableStock[key]
        })
        availableStock = availableStock.availableStock
        if (value > availableStock) { // 伪代码
            cb('盲盒商品件数不能大于库存数量');
        } else {
            cb();
        }
    }
    // 盲盒商品试玩件数校验
    function demoStockValidator (rule, value, cb) {
        let fields = rule.field.split('.')
        fields.pop()
        let commodityStock = vm.dialogForm
        fields.map(key => {
            commodityStock = commodityStock[key]
        })
        commodityStock = commodityStock.commodityStock
        if (value > commodityStock) { // 伪代码
            cb('试玩盲盒件数不能大于盲盒商品件数数量');
        } else {
            cb();
        }
    }
    // 盲盒试玩件数校验
    function returnRatioValidator(rule, value, cb){
        console.log('value' , Number(value) )
      value =  Number(value) 
        if(!(/^[0-9]+.?[0-9]*/).test(value)){
            cb('回收比例只能为数字');
        }else if (value < 80 || value > 200) { // 伪代码
            cb('回收比例最小值为80，最大值为200');
        } else {
            cb();
        }
    }
</script>
</body>
<!--  /Body -->

</html>